package com.example.demon.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demon.dao.AdminDao;
import com.example.demon.entity.Admin;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailService implements UserDetailsService {
    @Autowired
    AdminDao adminDao;


    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_name", s);
        Admin admin = adminDao.selectOne(queryWrapper);
        List<GrantedAuthority> authorities = new ArrayList<>();
        GrantedAuthority role = new SimpleGrantedAuthority("ROLE_ADMIN");
        authorities.add(role);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        } else {
            return new User(admin.getUsername(), admin.getPassword(), authorities);
        }
    }
}
